﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Hawaii.Services.Client;
using Hawaii.Services.Client.Relay;

namespace PhoneApp1
{
    public partial class PivotPage1 : PhoneApplicationPage
    {
        public PivotPage1()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(PivotPage1_Loaded);
        }

        /// <summary>
        /// Gets the relay data context.
        /// </summary>
        private RelayContext RelayContext
        {
            get { return ((App)App.Current).RelayContext; }
        }

        private void DisplayMessage(string message, string caption)
        {
            this.Dispatcher.BeginInvoke(
                    delegate
                    {
                        MessageBox.Show(message, caption, MessageBoxButton.OK);
                    });
        }

        private void Join_Click(object sender, RoutedEventArgs e)
        {
            if (this.RelayContext.Endpoint == null)
            {
                this.DisplayMessage("Invalid Endpoint, restart application", "Error");
                return;
            }

            if (this.group_id_box.Text == "")
            {
                this.DisplayMessage("You must enter a registration ID", "Error");
                return;
            }

            Group group = new Group()
            {
                Name = this.group_name_box.Text,
                RegistrationId = this.group_id_box.Text,
                SecretKey = string.Empty
            };

            RelayService.JoinGroupAsync(HawaiiClient.HawaiiApplicationId,
                                        this.RelayContext.Endpoint,
                                        group,
                                        this.OnCompleteJoinGroup,
                                        group);
        }

        private void OnCompleteJoinGroup(GroupResult result)
        {
            Debug.Assert(result != null, "result is null");

            if (result.Status == Status.Success)
            {
                Group group = (Group)result.StateObject;
                Debug.Assert(group != null, "StateObject is null");

                this.RelayContext.Endpoint.Groups.Add(group);

                this.Refresh_Joined_List();

                this.DisplayMessage("You have joined group " + group.Name, "Groups Update");
            }
            else
            {
                this.DisplayMessage("You are already a member of this group", "Error");
            }
        }

        private void Leave_Click(object sender, RoutedEventArgs e)
        {
            if (this.RelayContext.Endpoint == null)
            {
                this.DisplayMessage("Invalid Endpoint, restart application", "Error");
                return;
            }

            PollGroup group_item = (PollGroup)this.joined_list.SelectedItem;
            if (group_item == null)
            {
                this.DisplayMessage("No group was selected", "Error");
                return;
            }

            Group group = this.RelayContext.Groups.Find(group_item.Registration_ID);
            if (group == null)
            {
                this.DisplayMessage("No group is selected in the list box.", "Error");
                return;
            }

            RelayService.LeaveGroupAsync(HawaiiClient.HawaiiApplicationId,
                                         this.RelayContext.Endpoint,
                                         group,
                                         this.OnCompleteLeaveGroup,
                                         group);
        }

        private void OnCompleteLeaveGroup(GroupResult result)
        {
            Debug.Assert(result != null, "result is null");

            if (result.Status == Status.Success)
            {
                Group group = (Group)result.StateObject;
                Debug.Assert(group != null, "StateObject is null");

                this.RelayContext.Endpoint.Groups.Remove(group.RegistrationId);

                this.Refresh_Joined_List();

                this.DisplayMessage("You have left group " + group.Name, "Groups Update");
            }
            else
            {
                this.DisplayMessage("You are already a member of this group", "Error");
            }
        }

        private void Refresh_Joined_List()
        {
            this.Dispatcher.BeginInvoke(
                delegate
                {
                    List<PollGroup> groupList = new List<PollGroup>();

                    foreach (Group group in this.RelayContext.Endpoint.Groups)
                    {
                        groupList.Add(new PollGroup(group.Name, group.RegistrationId, group.Max_Number));
                    }

                    this.joined_list.ItemsSource = groupList;
                });
        }

        public void delgRefreshPollList()
        {
            this.Dispatcher.BeginInvoke(
                       delegate
                       {
                           RefreshPollList();
                       });
        }

        private void RefreshPollList()
        {
            pollList.Items.Clear();
            foreach (Poll p in ((App)App.Current).fileStorage.df.polls)
            {
                pollList.Items.Add(p);
                
            }
        }

        private void PivotPage1_Loaded(object sender, RoutedEventArgs e)
        {
            string pivot_item = this.NavigationContext.QueryString["parameter"];

            if (pivot_item.Equals("Groups"))
            {
                myGroupsPolls.SelectedItem = Groups;
            }
            else
            {
                myGroupsPolls.SelectedItem = Polls;
            }

            ((App)App.Current).RelayContext.CheckForMessages(this.delgRefreshPollList);
            RefreshPollList();
            this.Refresh_Joined_List();
        }

        private void View_Click(object sender, RoutedEventArgs e)
        {
            if (pollList.SelectedIndex == -1)
            {
                DisplayMessage("Select a poll first.", "Error");
                return;
            }
            NavigationService.Navigate(new Uri("/Poll1.xaml?guid=" + ((Poll)pollList.SelectedItem).guid.ToString(), UriKind.Relative));
        }


        private void Delete_Click(object sender, RoutedEventArgs e)
        {
            if (pollList.SelectedIndex == -1)
            {
                DisplayMessage("Select a poll first.", "Error");
                return;
            }
            ((App)App.Current).fileStorage.df.polls.Remove(pollList.SelectedItem as Poll);
            RefreshPollList();

        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.GoBack();
        }


        private void ViewResult_Click(object sender, RoutedEventArgs e)
        {
            if (pollList.SelectedIndex == -1)
            {
                DisplayMessage("Select a poll first.", "Error");
                return;
            }
            NavigationService.Navigate(new Uri("/ViewResults.xaml?guid=" + ((Poll)pollList.SelectedItem).guid.ToString(), UriKind.Relative));

        }
        
    }
}
